package controller

import (
	"github.com/cy77cc/hioshop/models"
	"github.com/cy77cc/hioshop/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

type CatalogHandler struct{}

type payload struct {
	Id   int `json:"id"`
	Page int `json:"page"`
	Size int `json:"size"`
}

func (CatalogHandler) GetCurrentList(ctx *gin.Context) {
	res := utils.NewResponse()
	p := payload{}
	goods := models.Goods{}
	err := ctx.ShouldBind(&p)
	if err != nil {
		res.SetRes(1, "参数解析失败", err)
		ctx.JSON(http.StatusOK, res)
		return
	}

	list := make([]models.Goods, 0, 16)

	if p.Id == 0 {

		list, err = goods.GetGoodsAll(p.Page, p.Size, map[string]any{
			"is_on_sale": 1,
			"is_delete":  0,
			"is_index":   0,
		})
		if err != nil {
			res.SetRes(1, "未找到商品，或商品为空", err)
			ctx.JSON(http.StatusOK, res)
			return
		}
	} else {
		list, err = goods.GetGoodsByCategoryId(uint(p.Id), p.Page, p.Size)
		if err != nil {
			res.SetRes(1, "未找到商品，或商品为空", err)
			ctx.JSON(http.StatusOK, res)
			return
		}
	}

	data := make(map[string]any)
	data["count"] = len(list)
	data["totalPage"] = len(list) / p.Page
	data["currentPage"] = p.Page
	data["pageSize"] = p.Page
	data["data"] = list
	res.SetRes(0, "success", data)
	ctx.JSON(http.StatusOK, res)

}

func (CatalogHandler) Current(ctx *gin.Context) {
	id := ctx.Query("id")
	res := utils.NewResponse()
	if id == "" {
		res.SetRes(1, "参数错误", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}
	category := models.Category{}
	data, err := category.GetCategoriesById(id)
	if err != nil {
		res.SetRes(1, "未能找到商品", err)
		ctx.JSON(http.StatusOK, res)
		return
	}

	res.SetRes(0, "success", data)
	ctx.JSON(http.StatusOK, res)
}
